import { ref, computed } from "vue";
import router from "../../../router";
import { useUserStore } from "../../../store/user";
import { getOrderList, findOrderStatus } from "../../../service/pay/";
import {
  getHistoryRecords,
  removeAllHistroyRecord,
  getCollectList,
  cancelCollect,
  getMsgList,
  getPlanList
} from "../../../service/personal";
import moment from "moment";

export const navigateToDetail = (id: string, searchType: string) =>
  window.open(
    `${location.origin}/detail?id=${id}&searchType=${searchType}`,
    "_blank"
  );

export const useFavoriteHooks = (
  type: "favorite" | "care" | "plan" = "favorite"
) => {
  const showBatchHandleBtn = ref(false);
  const dataList = ref<any[]>([]);
  const checkList = ref<any[]>([]);
  const checkAll = ref(false);
  const isIndeterminate = ref(false);

  // 请求收藏列表
  getCollectList().then((res: any) => {
    if (type === "favorite") {
      dataList.value = res.data.filter((item: any) => item.sourceType != "2");
    } else if (type === "care") {
      dataList.value = res.data.filter((item: any) => item.sourceType == "2");
    }
  });

  const handleCheckAllChange = (val: boolean) => {
    checkList.value = val ? dataList.value : [];
    isIndeterminate.value = false;
  };
  const handleCheckedCitiesChange = (value: string[]) => {
    const checkedCount = checkList.value.length;
    checkAll.value = checkedCount === dataList.value.length;
    isIndeterminate.value =
      checkedCount > 0 && checkedCount < dataList.value.length;
  };

  // 取消收藏
  const cancelFavorite = (idx?: number) => {
    if (typeof idx === "number") {
      cancelCollect({ collectIds: [dataList.value[idx].id + ""] });
      return dataList.value.splice(idx, 1);
    }

    if (!checkList.value.length) return false;
    ElMessageBox.confirm("是否要取消当前已选资源的收藏?", "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      // 拷贝一份当前已选列表
      let newCheckList: any[] | null = [...checkList.value];

      cancelCollect({ collectIds: checkList.value.map((item) => item.id) });

      for (let i = 0; i < newCheckList.length; i++) {
        const item = newCheckList[i];

        // 找到当前item在收藏列表的索引
        const realIdx = dataList.value.findIndex((j) => j === item);

        dataList.value.splice(realIdx, 1);
      }

      // 删除完勾选数据后,清空checkList并充值全选check的状态
      isIndeterminate.value = false;
      checkList.value = [];
      newCheckList = null;
      showBatchHandleBtn.value = false;
    });
  };

  return {
    dataList,
    checkList,
    checkAll,
    isIndeterminate,
    handleCheckAllChange,
    handleCheckedCitiesChange,
    showBatchHandleBtn,
    cancelFavorite
  };
};

export const useOrdersHooks = () => {
  const activeBar = ref("all");
  const orderList = ref<any[]>([]);
  const userStore = useUserStore();

  // 请求订单列表
  getOrderList().then((res: any) => {
    orderList.value = res.data;
  });

  // 支付二维码弹窗状态
  const payCodePopupStatus = ref(false);

  // 支付二维码地址
  const codeUrl = ref("");
  const orderId = ref("");
  let timer: any = null;
  // 打开支付二维码
  const openCodePopup = (item: any) => {
    // 清空定时任务状态
    if (timer) {
      clearInterval(timer);
      timer = null;
    }

    // 打开支付二维码弹窗
    payCodePopupStatus.value = true;

    // 开始轮询订单支付结果
    timer = setInterval(() => {
      findOrderStatus(item.orderId).then((res: any) => {
        if (res.data) {
          clearInterval(timer);
          timer = null;
          ElMessageBox.alert("支付完成", "提示", {
            confirmButtonText: "确定",
            type: "success",
            center: true,
            callback: async () => {
              // 重新请求用户数据以及订单列表数据
              await userStore.getUserInfo();
              userStore.updateUserAuth();
              await getOrderList().then((res: any) => {
                orderList.value = res.data;
              });
              payCodePopupStatus.value = false;
            }
          });
        }
      });
    }, 5000);
    // 根据订单id去请求支付二维码
    codeUrl.value = item.payUrl;
    orderId.value = item.orderId;
  };

  // 关闭订单
  const closeOrder = () => {};

  // 完成支付
  const overPay = () => {
    // 请求订单状态是否完成
    findOrderStatus(orderId.value).then(async (res: any) => {
      if (res.data) {
        clearInterval(timer);
        timer = null;

        // 重新请求用户数据以及订单列表数据
        await userStore.getUserInfo();
        getOrderList().then((res: any) => {
          orderList.value = res.data;
        });
      }
    });
    clearInterval(timer);
    timer = null;
    // 关闭弹窗
    payCodePopupStatus.value = false;
  };

  // 路由离开时销毁定时器
  // onBeforeRouteLeave((to, from) => {

  // })

  return {
    activeBar,
    orderList,
    openCodePopup,
    closeOrder,
    payCodePopupStatus,
    overPay,
    codeUrl
  };
};

export const useHistoryRecordHooks = () => {
  // 请求所有历史记录
  getHistoryRecords({ pageNum: 1, pageSize: 500 }).then((res) => {
    // 将遍历到的数据转换为需要的数据格式
    const today = moment().startOf("day");

    res.rows.forEach((item: any) => {
      const date = moment(item.createTime);

      //获取时间相差的天数
      const hoursDifference = date.diff(today, "hours");

      console.log(hoursDifference);

      if (hoursDifference > 0) {
        historyRecords.value[0].records.push(item);
      } else if (hoursDifference < 0 && hoursDifference > -24) {
        historyRecords.value[1].records.push(item);
      } else if (hoursDifference < -72 && hoursDifference > -168) {
        historyRecords.value[2].records.push(item);
      } else if (hoursDifference <= -168) {
        historyRecords.value[3].records.push(item);
      }
    });
  });

  // 显示操作面板
  const showBatchHandleBtn = ref(false);

  // 浏览记录
  const historyRecords = ref<any[]>([
    {
      time: "今天",
      records: []
    },
    {
      time: "昨天",
      records: []
    },
    {
      time: "三天前",
      records: []
    },
    {
      time: "七天前",
      records: []
    }
  ]);

  // 浏览记录长度
  const historyRecordLen = computed(() => {
    const allRecords = historyRecords.value
      .map((item: any) => item["records"])
      .flat();

    return allRecords.length;
  });

  // 清空所有浏览记录
  const clearHistoryRecords = () => {
    ElMessageBox.confirm("是否要清空所有浏览记录?", "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(async () => {
      // 发送网络请求
      await removeAllHistroyRecord();
      historyRecords.value.forEach((item: any) => {
        item["records"] = [];
      });
    });
  };

  // 清空单个浏览记录
  const removeRecord = (perIdx: number, idx: number) => {
    historyRecords.value[perIdx].records.splice(idx, 1);
  };

  return {
    showBatchHandleBtn,
    clearHistoryRecords,
    historyRecords,
    removeRecord,
    historyRecordLen
  };
};

export const usePersonalInfoHooks = () => {
  const userStore = useUserStore();
  userStore.getUserInfo();

  const userInfo = computed((): any => userStore.userInfo);

  // 跳转到VIP界面
  const openVip = () => {
    router.push({ path: "/vipCenter" });
  };

  // vip图标hover文字
  const vipIconHoverTip = computed(() => {
    if (userInfo.value.vip == 0) {
      return "您还不是本站会员";
    } else if (userInfo.value.vip == 1) {
      return "您是尊敬的透策会员";
    } else if (userInfo.value.vip == 2) {
      return "您是尊敬的透策超级会员";
    }
  });

  /**
   * 头像上传
   */
  const beforeUpload = (file: any) => {
    const size = Math.round(file.size / 1000 / 1000);
    const type = file.type.split("/")[1];

    if (size > 5) {
      ElMessage({
        type: "warning",
        message: "头像大小不能大于5M"
      });
      return false;
    }
  };

  const avatarUploaded = (res: any) => {
    userStore.getUserInfo();
    console.log(res);
  };
  return { openVip, vipIconHoverTip, userInfo, beforeUpload, avatarUploaded };
};

export const useMsgHooks = () => {
  const userStore: any = useUserStore();

  userStore.userInfo.unReadMessage = 0;

  const msgList = ref();
  // 请求消息列表
  getMsgList().then((res) => {
    msgList.value = res.rows;
  });

  return { msgList };
};

export const usePlanHooks = () => {
  const dataList = ref([]);

  // 请求规划列表
  getPlanList().then((res) => {
    dataList.value = res.data;
  });

  const goPlanDetailPage = (item: any) => {
    const { id, companyId, companyName, revenueScale } = item;
    window.open(
      `${location.origin}/matching?id=${id}&name=${companyName}&companyId=${companyId}&scale=${revenueScale}`
    );
  };

  return { dataList, goPlanDetailPage };
};
